# coding:UTF-8
"""
    测试文件
    Test file
"""
import time
import datetime
import platform
import struct
import lib.device_model as deviceModel
from lib.data_processor.roles.jy901s_dataProcessor import JY901SDataProcessor
from lib.protocol_resolver.roles.wit_protocol_resolver import WitProtocolResolver

welcome = """
欢迎使用维特智能示例程序    Welcome to the Wit-Motoin sample program
"""
_writeF = None                    #写文件  Write file
_IsWriteF = False                 #写文件标识    Write file identification

class JY901S():
    def __init__(self, data):
        print(welcome)
        """
        初始化一个设备模型   Initialize a device model
        """
        device = deviceModel.DeviceModel(
            "我的JY901",
            WitProtocolResolver(),
            JY901SDataProcessor(),
            "51_0"
        )
        self.data = data

        if (platform.system().lower() == 'linux'):
            device.serialConfig.portName = "/dev/ttyUSB1"  # 设置串口   Set serial port
        else:
            device.serialConfig.portName = "COM6"  # 设置串口   Set serial port
        device.serialConfig.baud = 115200  # 设置波特率  Set baud rate
        device.openDevice()  # 打开串口   Open serial port

        device.dataProcessor.onVarChanged.append(self.onUpdate)  # 数据更新事件 Data update event


    def readConfig(self, device):
        """
        读取配置信息示例    Example of reading configuration information
        :param device: 设备模型 Device model
        :return:
        """
        tVals = device.readReg(0x02,3)  #读取数据内容、回传速率、通讯速率   Read data content, return rate, communication rate
        if (len(tVals)>0):
            print("返回结果：" + str(tVals))
        else:
            print("无返回")
        tVals = device.readReg(0x23,2)  #读取安装方向、算法  Read the installation direction and algorithm
        if (len(tVals)>0):
            print("返回结果：" + str(tVals))
        else:
            print("无返回")

    def setConfig(self,device):
        """
        设置配置信息示例    Example setting configuration information
        :param device: 设备模型 Device model
        :return:
        """
        device.unlock()                # 解锁 unlock
        time.sleep(0.1)                # 休眠100毫秒    Sleep 100ms
        device.writeReg(0x03, 6)       # 设置回传速率为10HZ    Set the transmission back rate to 10HZ
        time.sleep(0.1)                # 休眠100毫秒    Sleep 100ms
        device.writeReg(0x23, 0)       # 设置安装方向:水平、垂直   Set the installation direction: horizontal and vertical
        time.sleep(0.1)                # 休眠100毫秒    Sleep 100ms
        device.writeReg(0x24, 0)       # 设置安装方向:九轴、六轴   Set the installation direction: nine axis, six axis
        time.sleep(0.1)                # 休眠100毫秒    Sleep 100ms
        device.save()                  # 保存 Save

    def AccelerationCalibration(self,device):
        """
        加计校准    Acceleration calibration
        :param device: 设备模型 Device model
        :return:
        """
        device.AccelerationCalibration()                 # Acceleration calibration
        print("加计校准结束")

    def FiledCalibration(self,device):
        """
        磁场校准    Magnetic field calibration
        :param device: 设备模型 Device model
        :return:
        """
        device.BeginFiledCalibration()                   # 开始磁场校准   Starting field calibration
        if input("请分别绕XYZ轴慢速转动一圈，三轴转圈完成后，结束校准（Y/N)？").lower()=="y":
            device.EndFiledCalibration()                 # 结束磁场校准   End field calibration
            print("结束磁场校准")

    def onUpdate(self, deviceModel):
        """
        数据更新事件  Data update event
        :param deviceModel: 设备模型    Device model
        :return:
        """
        '''print("芯片时间:" + str(deviceModel.getDeviceData("Chiptime"))
             , " 温度:" + str(deviceModel.getDeviceData("temperature"))
             , " 加速度：" + str(deviceModel.getDeviceData("accX")) +","+  str(deviceModel.getDeviceData("accY")) +","+ str(deviceModel.getDeviceData("accZ"))
             ,  " 角速度:" + str(deviceModel.getDeviceData("gyroX")) +","+ str(deviceModel.getDeviceData("gyroY")) +","+ str(deviceModel.getDeviceData("gyroZ"))
             , " 角度:" + str(deviceModel.getDeviceData("angleX")) +","+ str(deviceModel.getDeviceData("angleY")) +","+ str(deviceModel.getDeviceData("angleZ"))
            , " 磁场:" + str(deviceModel.getDeviceData("magX")) +","+ str(deviceModel.getDeviceData("magY"))+","+ str(deviceModel.getDeviceData("magZ"))
            , " 经度:" + str(deviceModel.getDeviceData("lon")) + " 纬度:" + str(deviceModel.getDeviceData("lat"))
            , " 航向角:" + str(deviceModel.getDeviceData("Yaw")) + " 地速:" + str(deviceModel.getDeviceData("Speed"))
             , " 四元素:" + str(deviceModel.getDeviceData("q1")) + "," + str(deviceModel.getDeviceData("q2")) + "," + str(deviceModel.getDeviceData("q3"))+ "," + str(deviceModel.getDeviceData("q4"))
              )'''
        self.data.collect_scg_data([[deviceModel.getDeviceData("accX"),deviceModel.getDeviceData("accY"),deviceModel.getDeviceData("accZ")],[deviceModel.getDeviceData("gyroX"),deviceModel.getDeviceData("gyroY"),deviceModel.getDeviceData("gyroZ")]])


